from .relys import BitSet
from .relys import Chip

class PROM(Chip):
    def __init__(self, awidth, dwidth, filename):
        super().__init__(awidth+dwidth*2, [0, awidth+dwidth], [awidth+dwidth, awidth+dwidth*2])
        self.ADDR = self.pinIN@[0, awidth]
        self.DAT = self.pinIN@[awidth, awidth+dwidth]
        self.addrlen = pow(2, awidth)
        self.width = dwidth
        with open(filename, "rb") as prom :
            self.rom = BitSet(prom.read((pow(2, awidth)*dwidth)//8))
        self._dat = self.read_rom(0)
        self.pinOUT(self._dat())
    def read_rom(self, addr):
        return self.rom@[addr*self.width, (addr+1)*self.width]
    def view(self):
        for i in range(self.rom.width//8) : 
            if (i%8)==0 : print("{:0>4X}".format(i), end=" : ")
            print("{:<0X>}  ".format(self.rom[i:i+8]), end="")
            if (i%8)==7 : print()

@PROM.keyframe(-1)
def _frame(chip):
    chip._dat = chip.read_rom(int(chip.ADDR()))
    chip.pinOUT(chip._dat())
    return chip

if __name__ == "__main__":
    rom = PROM(7,16,"~/linux_workspace/Simulator/lib/bin/8bit.bin")
    for j in range(10):
        rom.ADDR(j)
        for i in range(rom.maxframe+1):
            rom.update(i)
            print(f"<frame>:[{i}]", rom)

